package com.mangguo.tingjian.user.controller;


import com.mangguo.tingjian.common.Result;
import com.mangguo.tingjian.user.controller.req.UserImageReq;
import com.mangguo.tingjian.user.dto.*;
import com.mangguo.tingjian.user.service.IDwUserActiveAppService;
import com.mangguo.tingjian.util.CvsUtils;
import com.mangguo.tingjian.util.DateUtils;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.atomic.AtomicLong;

/**
 * <p>
 * 激活用户-APP 前端控制器
 * </p>
 *
 * @author auto
 * @since 2019-11-23
 */
@RestController
@RequestMapping("/user/dw-user-active-app")
@AllArgsConstructor
public class DwUserActiveAppController {

    private final IDwUserActiveAppService dwUserActiveAppService;


    /**
     * 累计激活用户数
     * @return
     */
    @GetMapping("/unique-imei/all")
    public Result<Long> appAllUserNum(){
        return Result.success(dwUserActiveAppService.countAllUniqueImei());
    }


    /**
     * 今日新增激活用户数
     * @return
     */
    @GetMapping("/unique-imei/today")
    public Result<Long> appUserNumToday(){
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
        Integer start = Integer.valueOf(simpleDateFormat.format(new Date()));
        return Result.success(dwUserActiveAppService.countUniqueImeiBetweenDate(start, start));
    }

    /**
     * 新增激活用户数按月份统计
     * @return
     */
    @GetMapping("/unique-imei/month")
    public Result<List<CountResult>> appUserCountByMonth(){
        return Result.success(dwUserActiveAppService.countUniqueImeiByMonth());
    }

    /**
     * 新增激活用户数按日统计（14天）
     * @return
     */
    @GetMapping("/unique-imei/date")
    public Result<List<CountResult>> userCountByDate(){
        Integer end = DateUtils.getTodayInt();
        Integer start = DateUtils.addDay(end, -14);
        Map<Integer, CountResult> map = new HashMap<>();
        DateUtils.getBetweenDates(start, end).forEach(date -> {
            CountResult countResult = new CountResult();
            countResult.setMDate(date);
            countResult.setCount(0L);
            map.put(date, countResult);
        });
        dwUserActiveAppService.countUniqueImeiByDate(start, end).forEach(countResult -> {
            map.get(countResult.getMDate()).setCount(countResult.getCount());
        });
        List<CountResult> results = new ArrayList<>();
        DateUtils.getBetweenDates(start, end).forEach(date -> {
            results.add(map.get(date));
        });
        return Result.success(results);
    }

    /**
     *  新增激活用户数按月份统计
     * @return
     */
    @GetMapping("/unique-imei/month/download")
    public void userCountByMonthDownload(HttpServletResponse response){
        List<CountResult> countResults = dwUserActiveAppService.countUniqueImeiByMonth();
        List<List<String>> list = new ArrayList<>();
        list.add(Arrays.asList("日期", "人数"));
        for(CountResult countResult : countResults){
            list.add(Arrays.asList(countResult.getMYear() + "-" + countResult.getMMonth(), countResult.getCount().toString()));
        }
        CvsUtils.downloadCvs(response, "APP新增用户月份统计", list);
    }


    /**
     * 新增激活用户数按日统计
     * @return
     */
    @PostMapping("/unique-imei/user-image/date")
    public Result<List<CountResult>> appUserImageCountByDateBetweenDate(@RequestBody UserImageReq userImageReq){
        return Result.success(dwUserActiveAppService.countUniqueImeiByDateBetweenDate(userImageReq));
    }

    /**
     * 新增激活渠道数前五
     * @return
     */
    @PostMapping("/unique-imei/user-image/channel")
    public Result<List<ChannelResultDto>> appUserImageCountByChannelBetweenDate(@RequestBody UserImageReq userImageReq){
        List<ChannelResultDto> channelResultDtos = new LinkedList<>();
        List<ChannelResult> channelResults = dwUserActiveAppService.countUniqueImeiByChannelIdBetweenDate(userImageReq);
        channelResults.stream()
                .filter(e -> e.getChannelId() != null)
                .forEach(e -> channelResultDtos.add(new ChannelResultDto(e.getCount(), e.getChannelId())));
        channelResults.stream()
                .filter(e -> e.getSubchannelId() != null)
                .forEach(e -> channelResultDtos.add(new ChannelResultDto(e.getCount(), e.getSubchannelId())));
        channelResultDtos.sort((o1, o2) -> Math.toIntExact(o2.getCount() - o1.getCount()));
        return Result.success(channelResultDtos);
    }

    /**
     * 新增激活城市前五
     * @return
     */
    @PostMapping("/unique-imei/user-image/city")
    public Result<List<CityResult>> appUserImageCountByCityBetweenDate(@RequestBody UserImageReq userImageReq){
        return Result.success(dwUserActiveAppService.countUniqueImeiByCityBetweenDate(userImageReq));
    }

    /**
     * 新增激活省份前五
     * @return
     */
    @PostMapping("/unique-imei/user-image/province")
    public Result<List<ProvinceResult>> appUserImageCountByProvinceBetweenDate(@RequestBody UserImageReq userImageReq){
        return Result.success(dwUserActiveAppService.countUniqueImeiByProvinceBetweenDate(userImageReq));
    }

    /**
     * 新增激活手机品牌前五百分比
     * @return
     */
    @PostMapping("/unique-imei/user-image/platform")
    public Result<List<PlatformResult>> appUserImageCountByPlatformBetweenDate(@RequestBody UserImageReq userImageReq){
        List<PlatformResult> list = dwUserActiveAppService.countUniqueImeiByPlatformBetweenDate(userImageReq);
        AtomicLong sum = new AtomicLong(0L);
        list.forEach(platformResult -> sum.addAndGet(platformResult.getCount()));
        list.forEach(platformResult -> platformResult.setRatio(platformResult.getCount().doubleValue() / sum.doubleValue()));
        if (list.size() > 5){
            PlatformResult other = PlatformResult.builder().platform("其他").count(0L).ratio(0d).build();
            for (int i = 5; i < list.size(); i++){
                other.setCount(other.getCount() + list.get(i).getCount());
                other.setRatio(other.getRatio() + list.get(i).getRatio());
            }
            list = list.subList(0 ,5);
            list.add(other);
        }
        return Result.success(list);
    }


    /**
     * 新增激活手机系统
     * @return
     */
    @PostMapping("/unique-imei/user-image/system")
    public Result<List<SystemResult>> appUserImageCountBySystemBetweenDate(@RequestBody UserImageReq userImageReq){
        List<SystemResult> list = dwUserActiveAppService.countUniqueImeiBySystemBetweenDate(userImageReq);
        AtomicLong sum = new AtomicLong(0L);
        list.forEach(e -> sum.addAndGet(e.getCount()));
        list.forEach(e -> e.setRatio(e.getCount().doubleValue() / sum.doubleValue()));
        return Result.success(list);
    }


}
